#include <yatak/yatak.h>
#include <yatak/kheap.h>
#include <keyboard.h>
#include <string.h>
#include <screen.h>
#include <shell.h>
#include <users.h>

void su (const char * user)
{
	char * dbuff;
	char uname [256] = {'\0'};
	char passwd [256];
	int seek = 0;
	strcpy (uname, user);
	fs_node_t *file = finddir_fs(GetCurrentNodeDir(), "user.conf");
	if (!file)
	{
		dprintf ("[su] Cannot open file: user.conf\n");
		return;
	}
	do
	{
		dbuff = rsa_decoder(file,&seek);
		if (!dbuff)
			break;
		
		char * param = (char *) kmalloc(sizeof(char)*256);
		char * sparam = param;
		strcpy (param, dbuff);
		char * line = strsep (&param," ");
		if (line)
		{
			if (strcmp (line, user))
			{
				kfree (dbuff);
				kfree (sparam);
				continue;
			}
			strcpy (uname, user);
			kfree (dbuff);
			kfree (sparam);
			break;
		}
		kfree (dbuff);
		kfree (sparam);
	}
	while (1);
	if (uname [0] == '\0')
	{
		kprintf ("Unknown ID: %s\n",user);
		return;
	}
	kprintf ("Password: ");
	in_string_passwd (passwd, 256);
	kprintf ("\n%s:%s\n",uname, passwd);
	int ret = login (uname, passwd);
	if (ret == -1 || ret == -2)
	{
		kprintf ("Incorrect password...\n");
		return;
	}
	init_user ();
}
